import Cookies from 'js-cookie';
import { login, getUserInfo, logout } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';
import { Message } from 'element-ui';
const UserIDKey = 'User-Userid';
const UserNameKey = 'User-username';
const IdentityKey = 'User-identity';
const RoleKey = 'User-role';

const user = {
  state: {
    token: getToken(),
    get userid(){
      return Cookies.get(UserIDKey);
    },
    get username(){
      return Cookies.get(UserNameKey);
    },
    get identity(){
      return Cookies.get(IdentityKey);
    },
    get role(){
      return Cookies.get(RoleKey);
    },
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USERID: (state, userid) => {
      Cookies.set(UserIDKey, userid);
    },
    SET_USERNAME: (state, username) => {
      Cookies.set(UserNameKey, username);
    },
    SET_IDENTITY: (state, identity) => {
      Cookies.set(IdentityKey, identity);
    },
    SET_ROLE: (state, role) => {
      Cookies.set(RoleKey, role);
    },
  },

  actions: {
    Login({ commit },userInfo) {
      let username = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        login(username, userInfo.password, userInfo.identity).then(response => {
          if (response.code==0){           
            let data = response.data;
            setToken(data.token);
            commit('SET_TOKEN', data.token);
            commit('SET_USERID', data.userid);
            commit('SET_USERNAME', data.username);
            commit('SET_IDENTITY', data.identity);
            commit('SET_ROLE', data.role);
            resolve(); 
          }
          else{
            Message.error(response.msg);
            reject();
          }
        }).catch(error => {
          reject(error);
        });
      });
    },
    GetInfo({ commit }){
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          if(response.code === 0){
            resolve();
          } else {
            Message.error(response.msg);
            reject();
          }
        }).catch( error => {
          reject(error);
        });  
      });    
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '');
          removeToken();
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        removeToken();
        resolve();
      });
    }
  }
};

export default user;